<template>
  <div class="permission_container">
     <!-- expand-row-keys	可以通过该属性设置 Table 目前的展开行，需要设置 row-key 属性才能使用，该属性为展开行的 keys 数组 -->
    <el-table
      border
      style="margin-bottom: 20px;"
      :data="menuPermissionList"
      :expand-row-keys="expandKeys"
      row-key="id"
    >
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="code" label="权限值" />
      <el-table-column prop="toCode" label="跳转权限值" />
      <el-table-column label="操作">
        <template slot-scope="{row}">
          <!-- 添加菜单or添加功能 -->
          <HintButton :disabled="row.level===4" type="primary" icon="el-icon-plus" size="mini" :title="getAddTitle(row.level)" 
          @click="toAddPermission(row)"  />
          <!--修改菜单or修改功能 -->
          <HintButton type="primary" icon="el-icon-edit" size="mini" :disabled="row.level===1"
          @click="toUpdatePermission(row)"   :title="row.level===4 ? '修改功能' : '修改菜单'" />

          <HintButton :disabled="row.level===1" type="danger" icon="el-icon-delete" size="mini" 
            title="删除" @click="removePermission(row)" />
          </template>
      </el-table-column>
    </el-table>


    <!-- 对话框 -->
    <el-dialog 
      :visible.sync="dialogPermissionVisible" 
      :title="dialogTitle" 
      @close="resetData">

      <el-form ref="permission" :model="permission"  label-width="120px" :rules="permissionRules" >
        <!-- !permission.id只有当添加事件触发时生效 -->
        <el-form-item label="父级名称" v-if="permission.level>2 && !permission.id">
          <el-input :value="permission.pname" style="width: 90%;" disabled/>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="permission.name" style="width: 90%;"/>
        </el-form-item>
        
        <el-form-item label="功能权限值" prop="code">
          <el-input v-model="permission.code" style="width: 90%;"/>
        </el-form-item>

        <el-form-item label="跳转路由权限值" prop="toCode" v-if="permission.level===4">
          <el-input v-model="permission.toCode" style="width: 90%;"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="resetData">取 消</el-button>
        <el-button type="primary"  @click="addOrUpdatePermission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PermissionList',
  
  data() {
    return {
      menuPermissionList: [], // 菜单列表
      expandKeys: [], // 需要自动展开的项
      dialogPermissionVisible: false, // 是否显示菜单权限的Dialog
      permission: { // 要操作的菜单权限对象
        level: 0,
        name: '',
        code: '',
        toCode: ''
      },

      // 菜单权限校验的规则
      menuRules:{
        name: [{ required: true, message: '名称必须输入' }],
        code: [{ required: true, message: '权限值必须输入' }]
      },

     // 按钮功能权限校验的规则
      btnRules:{
        name: [{ required: true, message: '名称必须输入' }],
        code: [{ required: true, trigger: 'blur', message: '功能权限值必须输入' }]
      }
    }
  },
  methods: {
    /* 1.获取到菜单列表 */
    async fetchPermissionList() {
      const result = await this.$API.permission.getPermissionList()
      if (result.code == 20000 || result.code == 200) {
        this.menuPermissionList = result.data.children
        // expand-row-keys的值应该为数据array 
        this.expandKeys = [this.menuPermissionList[0].id]
      }
    },
 

   /* 2.根据级别得到要显示的添加dialog的标题 Tooltip文字提示*/
  getAddTitle(level) {
    if (level === 1 || level === 2) {
      return '添加菜单'
    } else if (level === 3) {
      return '添加功能'
    }
  },

  /* 3.显示添加功能or添加菜单*/
  toAddPermission(row) {
    this.dialogPermissionVisible = true
    this.permission.pid = row.id
    this.permission.level = row.level + 1
    //每错的话用于表单的验证
    this.permission.type = this.permission.level === 4 ? 2 : 1
    this.permission.pname = row.name // 用于显示父名称, 但提交请求时是不需要的

    // 清除校验(必须在界面更新之后)
    // this.$refs.permission.clearValidate()
    this.$nextTick(() => this.$refs.permission.clearValidate())
  },

  /* 4.显示修改功能or修改菜单 */
  toUpdatePermission(row) {
    this.dialogPermissionVisible = true
    //使用浅拷贝 
    this.permission = { ...row }
    this.permission.type = this.permission.level === 4 ? 2 : 1


    // 清除校验(必须在界面更新之后)
    this.$nextTick(() => this.$refs.permission.clearValidate())
  },

  /* 5.取消事件，重置数据 */
    resetData() {
      //关闭对话框
      this.dialogPermissionVisible = false
      // 问题：重置初始数据，对话框消失过程中，隐藏的输入框会显示出来
      setTimeout(() => {
        this.permission = {
          level: 0,
          name: '',
          code: '',
          toCode: ''
        }
      }, 500)
      // this.$refs.permission.clearValidate()
    },


    /* 6.确定修改或新增事件 */
     addOrUpdatePermission() {
      //表单校验通过执行新增操作
      this.$refs.permission.validate(async (valid) => {
        if (valid) {
          // !!!解构+扩展运算符
          const {pname, ...perm} = this.permission // pname不需要携带
          const result = await this.$API.permission[perm.id ? 'updatePermission' : 'addPermission'](perm)
          console.log("没看明白啊",perm);
          if(result.code == 20000 || result.code == 200){
            this.$message.success(`${perm.id ? '修改' : '添加'}成功!`)
            this.resetData()
          }else{
            this.$message.error('失败')
          }
          this.fetchPermissionList()
        }
        
      })
     
    },


    /* 7.删除某个权限节点 */
    removePermission(row) {
      //MessageBox弹框
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$API.permission.removePermission(row.id)
        this.$message.success('删除成功')
        this.fetchPermissionList()
      }).catch((error) => {
        if(error === 'cancel'){
          this.$message.info('取消删除')
        }
      })
    },
  },

  computed: {
    /* 动态根据权限的等级来显示对话框Dialog的标题
     两种情况：
        1.修改功能或者是修改菜单 --- 有id值  level <= 3 ? 修改菜单：修改功能
        2.添加菜单或添加功能  ---没有id值 level <= 3? 添加菜单：添加功能

    */
    dialogTitle(){
        const {id, level} = this.permission
        if(id){
            return level ===4 ? "修改功能" : "修改菜单"
        }else{
          //只能添加2、3级菜单，4级为功能
            return level ===4 ? "添加功能" : `添加${level === 2 ?"二级":"三级"}菜单`
        }
    },
    /* 
    根据权限的等级来计算确定校验规则
    */
    permissionRules () {
      return this.permission.level===4 ? this.btnRules : this.menuRules
    }
  },
  mounted () {
    this.fetchPermissionList()
    //  console.log(this)
  }

 
}

</script>

<style scoped>
.permission_container{
  margin: 10px 0px;
}
</style>